﻿jQuery.fn.getBox = function() {
    return {
        left: $(this).offset().left,
        top: $(this).offset().top,
        width: $(this).outerWidth(),
        height: $(this).outerHeight()
    };
};

function setTime() {
    $('span.time').each(function(index) {
        var timeLeft = $(this).attr('timeleft');
        var timeString = '';
        var sec, hour, min, day, time = null;
        if (timeLeft < 1) {
            timeString = '&#272;&#227; h&#7871;t h&#7841;n';
        } else {
            sec = timeLeft - 60 * Math.floor(timeLeft / 60);
            timeLeft = Math.floor(timeLeft / 60);
            min = timeLeft - 60 * Math.floor(timeLeft / 60);
            timeLeft = Math.floor(timeLeft / 60);
            hour = timeLeft - 24 * Math.floor(timeLeft / 24);
            day = Math.floor(timeLeft / 24);
            if (day > 0) timeString = day + ' ng&#224;y ';
            if (hour > 0) timeString = timeString + hour + ' gi&#7901; ';
            if (min > 0) timeString = timeString + min + ' ph&#250;t ';
            if (sec > 0) timeString = timeString + sec + ' gi&#226;y';
            $(this).attr('timeleft', $(this).attr('timeleft') - 1);
        }
        $(this).html(timeString);
    });

    setTimeout("setTime()", 1000);
}

(function($) {

    $.fn.maxlength = function(settings) {

        if (typeof settings == 'string') {
            settings = { feedback: settings };
        }

        settings = $.extend({}, $.fn.maxlength.defaults, settings);

        function length(el) {
            var parts = el.value;
            if (settings.words)
                parts = el.value.length ? parts.split(/\s+/) : { length: 0 };
            return parts.length;
        }

        return this.each(function() {
            var field = this,
				$field = $(field),
				$form = $(field).parent(),
				limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'),
				$charsLeft = $form.find(settings.feedback);


            function limitCheck(event) {
                var len = length(this),
					exceeded = len >= limit,
					code = event.keyCode;

                if (!exceeded)
                    return;

                switch (code) {
                    case 8:  // allow delete
                    case 9:
                    case 17:
                    case 36: // and cursor keys
                    case 35:
                    case 37:
                    case 38:
                    case 39:
                    case 40:
                    case 46:
                        //case 65:
                        return;
                    default:
                        return settings.words && code != 32 && code != 13 && len == limit;
                }
            }

            var updateCount = function() {
                var len = length(field),
					diff = limit - len;

                $charsLeft.html(diff || "0");

                //truncation code
                if (settings.hardLimit && diff < 0) {
                    field.value = settings.words ?
                    //split by white space, capturing it in the result, then glue them back
						field.value.split(/(\s+)/, (limit * 2) - 1).join('') :
						field.value.substr(0, limit);

                    updateCount();
                }
            };

            $field.keyup(updateCount).change(updateCount);
            if (settings.hardLimit) {
                $field.keydown(limitCheck);
            }

            updateCount();
        });
    };

    $.fn.maxlength.defaults = {
        useInput: false,
        hardLimit: true,
        feedback: '.charsLeft',
        words: false
    };

})(jQuery);


(function($) {

    $.fn.autoResize = function(options) {

        // Just some abstracted details,
        // to make plugin users happy:
        var settings = $.extend({
            onResize: function() { },
            animate: false,
            animateDuration: 150,
            animateCallback: function() { },
            extraSpace: 20,
            limit: 500
        }, options);

        // Only textarea's auto-resize:
        this.filter('textarea').each(function() {

            // Get rid of scrollbars and disable WebKit resizing:
            var textarea = $(this).css({ resize: 'none', 'overflow-y': 'hidden' }),

            // Cache original height, for use later:
                origHeight = textarea.height(),

            // Need clone of textarea, hidden off screen:
                clone = (function() {

                    // Properties which may effect space taken up by chracters:
                    var props = ['height', 'width', 'lineHeight', 'textDecoration', 'letterSpacing'],
                        propOb = {};

                    // Create object of styles to apply:
                    $.each(props, function(i, prop) {
                        propOb[prop] = textarea.css(prop);
                    });

                    // Clone the actual textarea removing unique properties
                    // and insert before original textarea:
                    return textarea.clone().removeAttr('id').removeAttr('name').css({
                        position: 'absolute',
                        top: 0,
                        left: -9999
                    }).css(propOb).attr('tabIndex', '-1').insertBefore(textarea);

                })(),
                lastScrollTop = null,
                updateSize = function() {

                    // Prepare the clone:
                    clone.height(0).val($(this).val()).scrollTop(10000);

                    // Find the height of text:
                    var scrollTop = Math.max(clone.scrollTop(), origHeight) + settings.extraSpace,
                        toChange = $(this).add(clone);

                    // Don't do anything if scrollTip hasen't changed:
                    if (lastScrollTop === scrollTop) { return; }
                    lastScrollTop = scrollTop;

                    // Check for limit:
                    if (scrollTop >= settings.limit) {
                        $(this).css('overflow-y', '');
                        return;
                    }
                    // Fire off callback:
                    settings.onResize.call(this);

                    // Either animate or directly apply height:
                    settings.animate && textarea.css('display') === 'block' ?
                        toChange.stop().animate({ height: scrollTop }, settings.animateDuration, settings.animateCallback)
                        : toChange.height(scrollTop);
                };

            // Bind namespaced handlers to appropriate events:
            textarea
                .unbind('.dynSiz')
                .bind('keyup.dynSiz', updateSize)
                .bind('keydown.dynSiz', updateSize)
                .bind('change.dynSiz', updateSize);
        });

        // Chain:
        return this;

    };

})(jQuery);

$(document).ready(function() {
    $('#link-logout').click(function(e) {
        $.ajax({
            url: '/logout.aspx',
            beforeSend: function(xhr) {
                xhr.setRequestHeader("gm-ajax-request", 'gm-ajax-request');
            },
            data: {},
            dataType: 'json',
            type: 'post',
            async: true,
            success: function(results) {
                window.location.href = '/';
            },
            error: function(xhr) {
                window.location.href = '/';
            }
        });

        e.preventDefault();
    });
});
